/*******************************************************************************
 * Package: com.hngtrust.iir.report.controller
 * Type:    ReportController
 * Date:    2021/3/22 16:02
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.report.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.hngtrust.clickhouse.report.dto.*;
import com.hngtrust.clickhouse.report.entity.AppReport;
import com.hngtrust.clickhouse.report.entity.AppReportPic;
import com.hngtrust.clickhouse.report.entity.AppReportSentiment;
import com.hngtrust.clickhouse.report.service.AppReportPicService;
import com.hngtrust.clickhouse.report.service.AppReportSentimentService;
import com.hngtrust.clickhouse.report.service.AppReportService;
import com.hngtrust.framework.bind.ResponseInfo;
import com.hngtrust.framework.id.service.MyIdGenerator;
import com.hngtrust.framework.page.PageResult;
import com.hngtrust.framework.page.service.PageService;
import com.hngtrust.framework.security.util.SecurityUtils;
import com.hngtrust.iir.base.controller.vo.OptLogReqVO;
import com.hngtrust.iir.base.entity.Dict;
import com.hngtrust.iir.base.entity.IndustrySw;
import com.hngtrust.iir.base.entity.ReportType;
import com.hngtrust.iir.base.service.*;
import com.hngtrust.iir.company.entity.Company;
import com.hngtrust.iir.company.service.CompanyService;
import com.hngtrust.iir.constant.Constant;
import com.hngtrust.iir.dto.ReqDTO;
import com.hngtrust.iir.report.controller.dto.*;
import com.hngtrust.iir.report.entity.ReportPushScheme;
import com.hngtrust.iir.report.entity.ReportSchemeConfig;
import com.hngtrust.iir.report.entity.ReportUpload;
import com.hngtrust.iir.report.service.ReportPushSchemeService;
import com.hngtrust.iir.report.service.ReportPushService;
import com.hngtrust.iir.report.service.ReportSchemeConfigService;
import com.hngtrust.iir.report.service.ReportUploadService;
import com.hngtrust.iir.risk.controller.dto.ListReportPushReqVO;
import com.hngtrust.iir.user.entity.CollectInfo;
import com.hngtrust.iir.user.entity.TagRel;
import com.hngtrust.iir.user.entity.User;
import com.hngtrust.iir.user.service.CollectInfoService;
import com.hngtrust.iir.user.service.TagRelService;
import com.hngtrust.iir.user.service.UserService;
import com.hngtrust.iir.util.DateUtils;
import com.hngtrust.iir.util.FileUtils;
import com.hngtrust.iir.util.HtmlUtils;
import com.hngtrust.iir.util.ListUtil;
import com.tiger.util.MyHttpClient;
import com.tiger.web.annotation.DownloadMapping;
import com.tiger.web.annotation.UploadMapping;
import com.tiger.web.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
/**
 * 智能研报管理
 *
 * @author Keqiwei
 * @date 2021/3/22 16:02
 */
@Slf4j
@Api(tags = "智能研报管理")
@RestController
@RequestMapping("/report")
public class ReportController {
    
    @Autowired
    private PageService pageService;
    
    @Autowired
    private AppReportService reportService;
    
    @Autowired
    private AppReportPicService picService;
    
    @Autowired
    private ReportUploadService uploadService;
    
    @Autowired
    private TagRelService tagRelService;
    
    @Autowired
    private ReportSchemeConfigService schemeConfigService;
    
    @Autowired
    private DictService dictService;
    
    @Autowired
    private ReportPushSchemeService schemeService;
    
    @Autowired
    private IndustryService industryService;
    
    @Autowired
    private CompanyService companyService;
    
    @Autowired
    private ReportPushService reportPushService;

    @Autowired
    private IndustrySwService industrySwService;

    @Autowired
    private CollectInfoService collectInfoService;
    
    
    @Autowired
    @Qualifier("minIoFileService")
    private FileService fileService;
    
    // 本地文件服务
    @Autowired
    @Qualifier("localFileService")
    private FileService localFileService;
    
    @Value("${tiger.minio.address}")
    private String down;
    
    @Autowired
    private UserService userService;
    
    
    @Autowired
    private LogService logService;
    
    @Autowired
    private AppReportSentimentService appReportSentimentService;
    
    @Value("${tiger.minio.out.address}")
    private String minioAddress;
    
    @Autowired
    private ReportTypeService reportTypeService;
    
    @Autowired
    private AppReportPicService appReportPicService;
    
    /**
     *
     * 主键生成器
     */
    @Autowired
    private MyIdGenerator myIdGenerator;
    
    @Value("${ai.researchReportProcessing.url}")
    private String url;
    
    /**
     * minio文件地址
     */
    @Value("${upload.report.minio}")
    private String minioUpload;
    
    
    @ApiOperation("根据推送策略推送研报列表")
    @PostMapping("/removal-report")
    public ResponseInfo<PageResult<ListReportRespVO>> removalReport(
            @ApiParam("列表请求") @Valid @RequestBody ReqDTO<ReportPushReqVO> dto)  {
        PageResult<ListReportRespVO> pageResult = new PageResult<>();
        List<ListReportRespVO> list = new ArrayList<>();
        List<Integer> rank = new ArrayList<>();
        List<Integer> rankChange = new ArrayList<>();
        List<Integer> type = new ArrayList<>();
        List<String> industry = new ArrayList<>();
        List<String> source = new ArrayList<>();
        List<String> dataSource = new ArrayList<>();
        for (ReportPushReqVO.Schemes scheme : dto.getContent().getSchemes()) {
            if (scheme.getDataSource() != null){
                dataSource.addAll(scheme.getDataSource());
            }
            
            if (scheme.getSource() != null ){
                source.addAll(scheme.getSource());
            }
            
            if (scheme.getType() != null){
                type.addAll(scheme.getType());
            }
            
            if (scheme.getRank() != null){
                rank.addAll(scheme.getRank());
            }
    
            if (scheme.getRankChange() != null) {
                rankChange.addAll(scheme.getRankChange());
            }
            
            if (scheme.getIndustryIds() != null){
                List<String> code = industryService.queryByIds(scheme.getIndustryIds()).stream()
                        .map(i -> i.getCode().substring(0, 4)+"%").collect(Collectors.toList());
                industry.addAll(code);
    
            }
        }
        if (rank.isEmpty() && type.isEmpty() && industry.isEmpty() && rankChange.isEmpty() && dataSource.isEmpty() && source.isEmpty()){
            pageResult.setRows(new ArrayList<>());
            pageResult.setPage(new PageResult.PageResultInfo());
            return new ResponseInfo<>(pageResult);
        }
        String start = null;
        if (null != dto.getContent().getStartTime() && !dto.getContent().getStartTime().isEmpty()){
            start = dto.getContent().getStartTime();
        }
        String end = null ;
        if (null != dto.getContent().getEndTime() && !dto.getContent().getEndTime().isEmpty()){
           end  = dto.getContent().getEndTime()+" 23:59:59";
        }
        String ss = start;
        String e = end;
        ListReportPushDTO pushDTO = new ListReportPushDTO();
        pushDTO.setSource(source);
        pushDTO.setDataSource(dataSource);
        pushDTO.setStartTime(ss);
        pushDTO.setEndTime(e);
        pushDTO.setRankChange(rankChange);
        pushDTO.setRank(rank);
        pushDTO.setIndustryIds(industry);
        pushDTO.setType(type);
        PageResult<AppReport> page = pageService.page(dto.getPageParam(), () -> reportService.queryReportByScheme(pushDTO));
        List<String> reportIds = page.getRows().stream().map(a -> a.getId()).collect(Collectors.toList());
        List<AppReportSentiment> appReportSentiments = appReportSentimentService.queryByReportIds(reportIds);
        Map<String, Dict> reportLevel = dictService.queryDict("REPORT_LEVEL");
        Map<String, Dict> levelChange = dictService.queryDict("LEVEL_CHANGE");
        List<TagRel> tagRels = tagRelService
                .queryByTagIds(reportIds,
                        Constant.SCHEME_CONFIG_TYPE_RATING);
        for (AppReport row : page.getRows()) {
            ListReportRespVO vo = new ListReportRespVO();
            BeanUtils.copyProperties(row,vo);
            List<String> names = appReportSentiments.stream().filter(a -> {
                if (a.getReportId().equals(row.getId())) {
                    return true;
                } else {
                    return false;
                }
            }).map(a -> a.getEntity()).collect(Collectors.toList());
            if(names.size()>10){
                names = names.subList(0,10);
            }
            vo.setCompNames(names);
            if (!tagRels.isEmpty()){
                List<TagRel> tagNames = tagRels.stream().filter(t -> {
                    if (row.getId().equals(t.getDataId())) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
                vo.setLabels(tagNames);
            }
            if (null != row.getRank()){
                vo.setRankName(dictService.queryDictByCode(reportLevel,row.getRank().toString()).getBusiName());
            }
            if (null != row.getRankChange()){
                vo.setRankChangeName(dictService.queryDictByCode(levelChange,row.getRankChange().toString()).getBusiName());
            }
            if (null != row.getType()){
                ReportType rt = reportTypeService.queryReportType(row.getType().longValue());
                if(null != rt){
                    vo.setTypeName(rt.getName());
                }
            }
            list.add(vo);
        }
        pageResult.setRows(list);
        pageResult.setPage(page.getPage());
        return new ResponseInfo<>(pageResult);
    }

    
    @ApiOperation("根据公司获取研报列表")
    @PostMapping("/list-report-comp")
    public ResponseInfo<PageResult<ListReportRespVO>> listReportComp(
            @ApiParam("列表请求") @Valid @RequestBody ReqDTO<ListReportByCompIdsReqVO> dto) {
        AppReportSentiment appReportSentiment = new AppReportSentiment();
        appReportSentiment.setCompId(dto.getContent().getCompId());
        List<String> reportIds = appReportSentimentService.queryList(appReportSentiment).stream()
                .map(a -> a.getReportId()).collect(Collectors.toList());
        
        if (reportIds.isEmpty()) {
            return new ResponseInfo<>();
        } else {
            PageResult<AppReport> page = pageService.page(dto.getPageParam(), () -> reportService.queryListByIds(reportIds));
            PageResult<ListReportRespVO> pageResult = new PageResult<>();
            ListUtil<ListReportRespVO> listUtil = BeanUtils.instantiateClass(ListUtil.class);
            listUtil.copyList(page, pageResult, ListReportRespVO.class);
            Map<String, Dict> reportLevel = dictService.queryDict("REPORT_LEVEL");
            Map<String, Dict> levelChange = dictService.queryDict("LEVEL_CHANGE");
            for (ListReportRespVO vo : pageResult.getRows()) {
                TagRel tagRel = new TagRel();
                tagRel.setDataType(Constant.TAG_DATATYPE_REPORT);
                tagRel.setDataId(vo.getId());
                if (vo.getHtml() != null && vo.getHtml() != "") {
                    vo.setHtml(HtmlUtils.replaceHtmlTag(vo.getHtml(), minioAddress));
                }
                vo.setLabels(tagRelService.queryList(tagRel));
                if (vo.getFilePath() != null && !vo.getFilePath().isEmpty()) {
                    vo.setFilePath(HtmlUtils.filePathAppend(vo.getFilePath(), url));
                }
                if (null != vo.getRank()){
                    vo.setRankName(dictService.queryDictByCode(reportLevel,vo.getRank().toString()).getBusiName());
                }
                if (null != vo.getRankChange()){
                    vo.setRankChangeName(dictService.queryDictByCode(levelChange,vo.getRankChange().toString()).getBusiName());
                }
//                if (null != vo.getType() && null != reportTypeService.queryById(vo.getType().longValue())){
//                    vo.setTypeName(reportTypeService.queryById(vo.getType().longValue()).getName());
//                }
                vo.setContent(vo.getContent().trim());
                AppReportSentiment sentiment = new AppReportSentiment();
                sentiment.setReportId(vo.getId());
                List<String> compIds = appReportSentimentService.queryList(sentiment).stream().map(a -> a.getCompId()).collect(Collectors.toList());
                List<String> compNames = appReportSentimentService.queryList(sentiment).stream().map(a -> a.getEntity())
                        .collect(Collectors.toList());
                vo.setCompIds(compIds);
                if (compNames.size() >10){
                    int i = compNames.indexOf(dto.getContent().getCompName());
                    if (i<=9){
                        compNames = compNames.subList(0,10);
                    }else {
                        compNames=     compNames.subList(i-9,i+1);
                    }
                }
                vo.setCompNames(compNames);
            }
            return new ResponseInfo<>(pageResult);
        }
    }
    
    @ApiOperation("根据公司行业获取研报列表")
    @PostMapping("/list-report-comp-industry")
    public ResponseInfo<PageResult<ListReportRespVO>> listReportCompIndustry(
            @ApiParam("列表请求") @Valid @RequestBody ReqDTO<ListReportByCompIdsReqVO> dto) {
        Company company = companyService.queryById(Long.parseLong(dto.getContent().getCompId()));
        PageResult<ListReportRespVO> pageResult = new PageResult<>();
        if (company == null) {
            return new ResponseInfo<>(pageResult);
        }
        if (industryService.queryById(company.getIndustry()) == null) {
            return new ResponseInfo<>(pageResult);
        }
        String industryCode = HtmlUtils.getIndustryCode(industryService.queryById(company.getIndustry()));
        PageResult<AppReport> page = pageService.page(dto.getPageParam(), () -> reportService.queryListLikeIndustry(industryCode));
        
        ListUtil<ListReportRespVO> listUtil = BeanUtils.instantiateClass(ListUtil.class);
        listUtil.copyList(page, pageResult, ListReportRespVO.class);
        Map<String, Dict> reportLevel = dictService.queryDict("REPORT_LEVEL");
        Map<String, Dict> levelChange = dictService.queryDict("LEVEL_CHANGE");
        for (ListReportRespVO vo : pageResult.getRows()) {
            TagRel tagRel = new TagRel();
            tagRel.setDataType(Constant.TAG_DATATYPE_REPORT);
            tagRel.setDataId(vo.getId());
            if (vo.getHtml() != null && vo.getHtml() != "") {
                vo.setHtml(HtmlUtils.replaceHtmlTag(vo.getHtml(), minioAddress));
            }
            if (vo.getFilePath() != null && !vo.getFilePath().isEmpty()) {
                vo.setFilePath(HtmlUtils.filePathAppend(vo.getFilePath(), url));
            }
            if (vo.getFilePath() != null && !vo.getFilePath().isEmpty()) {
                vo.setFilePath(HtmlUtils.filePathAppend(vo.getFilePath(), url));
            }
            if (null != vo.getRank()){
                vo.setRankName(dictService.queryDictByCode(reportLevel,vo.getRank().toString()).getBusiName());
            }
            if (null != vo.getRankChange()){
                vo.setRankChangeName(dictService.queryDictByCode(levelChange,vo.getRankChange().toString()).getBusiName());
            }
//            if (null != vo.getType() && null != reportTypeService.queryById(vo.getType().longValue())){
//                vo.setTypeName(reportTypeService.queryById(vo.getType().longValue()).getName());
//            }
            vo.setLabels(tagRelService.queryList(tagRel));
            AppReportSentiment sentiment = new AppReportSentiment();
            sentiment.setReportId(vo.getId());
            List<String> compIds = appReportSentimentService.queryList(sentiment).stream().map(a -> a.getCompId()).collect(Collectors.toList());
            List<String> compNames = appReportSentimentService.queryList(sentiment).stream().map(a -> a.getEntity()).collect(Collectors.toList());
            vo.setCompIds(compIds);
            if (compNames.size() >10){
                compNames = compNames.subList(0,10);
            }
            vo.setCompNames(compNames);
        }
        
        return new ResponseInfo<PageResult<ListReportRespVO>>(pageResult);
    }
    
    @ApiOperation("观点列表")
    @PostMapping("/list-viewpoint")
    public ResponseInfo<PageResult<ListReportRespVO>> listViewpoint(
            @ApiParam("列表请求") @Valid @RequestBody ReqDTO<ListReportPushReqVO> dto) {
        ListReportPushDTO pushDTO = new ListReportPushDTO();
        BeanUtils.copyProperties(dto.getContent(), pushDTO);
        pushDTO.setTitle("%"+dto.getContent().getTitle()+"%");
        PageResult<AppReport> page = pageService.page(dto.getPageParam(), () -> reportService.queryListReport(pushDTO));
        PageResult<ListReportRespVO> pageResult = new PageResult<>();
        List<ListReportRespVO> list = new ArrayList<>();
        List<TagRel> tagRels = tagRelService.queryList(new TagRel());
        List<AppReportSentiment> appReportSentiments = appReportSentimentService.queryList(new AppReportSentiment());
        Map<String, Dict> reportLevel = dictService.queryDict("REPORT_LEVEL");
        Map<String, Dict> levelChange = dictService.queryDict("LEVEL_CHANGE");
        OptLogReqVO vo1 = new OptLogReqVO();
        vo1.setStatus(1);
        vo1.setOptContent("搜索"+dto.getContent().getTitle()+"检索研报");
        vo1.setOptModule(4);
        vo1.setOptType(3);
        logService.saveOptLog(vo1);
        
        for (AppReport report : page.getRows()) {
            ListReportRespVO vo = new ListReportRespVO();
            BeanUtils.copyProperties(report,vo);
            vo.setLabels(tagRels.stream().filter(t -> {
                if (Constant.TAG_DATATYPE_REPORT.equals(t.getDataId()) && vo.getId().equals(t.getDataId())) {
                    return true;
                } else {
                    return false;
                }
            }).collect(Collectors.toList()));
            
            if (vo.getFilePath() != null && !vo.getFilePath().isEmpty()) {
                vo.setFilePath(HtmlUtils.filePathAppend(vo.getFilePath(), url));
            }
    
            List<String> compIds = appReportSentiments.stream().filter(a -> {
                if (vo.getId().equals(a.getReportId())) {
                    return true;
                } else {
                    return false;
                }
            }).map(a -> a.getCompId()).collect(Collectors.toList());
            List<String> compNames = appReportSentiments.stream().filter(a -> {
                if (vo.getId().equals(a.getReportId())) {
                    return true;
                } else {
                    return false;
                }
            }).map(a -> a.getEntity()).collect(Collectors.toList());
            if (vo.getHtml() != null && vo.getHtml() != "") {
                vo.setHtml(HtmlUtils.replaceHtmlTag(vo.getHtml(), minioAddress));
            }
            if (null != report.getRank()){
                vo.setRankName(dictService.queryDictByCode(reportLevel,report.getRank().toString()).getBusiName());
            }
            if (null != report.getRankChange()){
                vo.setRankChangeName(dictService.queryDictByCode(levelChange,report.getRankChange().toString()).getBusiName());
            }
//            if (null != report.getType() && null != reportTypeService.queryById(report.getType().longValue())){
//                vo.setTypeName(reportTypeService.queryById(report.getType().longValue()).getName());
//            }
            vo.setCompIds(compIds);
            if (compNames.size() >10){
                compNames = compNames.subList(0,10);
            }
            vo.setCompNames(compNames);
            list.add(vo);
        }
        pageResult.setRows(list);
        pageResult.setPage(page.getPage());
        return new ResponseInfo<>(pageResult);
    }
    
    @ApiOperation("图表列表")
    @PostMapping("/list-chart")
    public ResponseInfo<PageResult<ListPicRespVO>> listChart(
            @ApiParam("列表请求") @Valid @RequestBody ReqDTO<ListReportPushReqVO> dto) {
        ListReportPushDTO pushDTO = new ListReportPushDTO();
        BeanUtils.copyProperties(dto.getContent(), pushDTO);
        List<ListPicRespVO> list = new ArrayList<>();
        
        PageResult<ListPicDTO> page = pageService.page(dto.getPageParam(), () -> picService.queryListByReport(pushDTO));
        PageResult<ListPicRespVO> pageResult = new PageResult<>();
        pageResult.setPage(page.getPage());
        for (ListPicDTO pic : page.getRows()) {
            ListPicRespVO vo = new ListPicRespVO();
            BeanUtils.copyProperties(pic, vo);
            TagRel tagRel = new TagRel();
            
            tagRel.setDataType(Constant.TAG_DATATYPE_REPORT);
            tagRel.setDataId(pic.getReportId());
            List<String> labels = tagRelService.queryList(tagRel).stream().map(t -> t.getTagName())
                    .collect(Collectors.toList());
            vo.setLabels(labels);
            vo.setUrl(HtmlUtils.filePathAppend(pic.getUrl(), minioAddress));
            list.add(vo);
        }
        pageResult.setRows(list);
        return new ResponseInfo<PageResult<ListPicRespVO>>(pageResult);
    }
    
    @ApiOperation("上传研报列表")
    @PostMapping("/list-upload-report")
    public ResponseInfo<PageResult<UploadReportRespVO>> listUploadReport(@ApiParam("上传文件") @Valid @RequestBody ReqDTO<Object> dto) {
        ReportUpload reportUpload = new ReportUpload();
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        PageResult<ReportUpload> page = pageService
                .page(dto.getPageParam(), () -> uploadService.queryByCreateUserId(loginUser.getId()));
        List<UploadReportRespVO> list = new ArrayList<>();
        for (ReportUpload upload : page.getRows()) {
            UploadReportRespVO vo = new UploadReportRespVO();
            BeanUtils.copyProperties(upload, vo);
            vo.setName(userService.queryById(upload.getCreateUserId()).getName());
            list.add(vo);
        }
        PageResult<UploadReportRespVO> pageResult = new PageResult();
        pageResult.setPage(page.getPage());
        pageResult.setRows(list);
        
        return new ResponseInfo<PageResult<UploadReportRespVO>>(pageResult);
    }
    
    @ApiOperation("删除上传研报")
    @PostMapping("/delete-upload-report")
    public ResponseInfo<Object> deleteUploadReport(@ApiParam("删除参数") @Valid @RequestBody DeleteUploadReportReqVO vo) {
        ReportUpload upload = new ReportUpload();
        BeanUtils.copyProperties(vo, upload);
        uploadService.modifyById(upload);
        return new ResponseInfo<Object>();
    }
    
    @ApiOperation("上传研报")
    @UploadMapping("/upload-report")
    public ResponseInfo<Object> uploadReport(@ApiParam("上传文件") @Valid @RequestParam(required = true) MultipartFile file)
            throws IOException {
        ReportUpload upload = new ReportUpload();
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        Long mysqlId = myIdGenerator.nextId();
        upload.setId(mysqlId);
        upload.setCreateUserId(loginUser.getId());
        upload.setFileName(file.getOriginalFilename());
        upload.setCreateTime(new Date());
        upload.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        String path = minioUpload + DateUtils.getTodayString() + "/";
        try {
            String directory = System.getProperty("java.io.tmpdir");
            String fileName = file.getOriginalFilename();
            File tempFile = new File(directory, fileName);
            file.transferTo(tempFile);//保存文件
            //把文件写入后再执行以下
            String retPath = fileService.upload(tempFile, path, true);
            upload.setFilePath(retPath);
            MyHttpClient myHttpClient = new MyHttpClient();
            UploadReportAIReqDTO bo = new UploadReportAIReqDTO();
            bo.setMysqlId(mysqlId);
            bo.setPathString(retPath);
            upload.setReportId(Constant.DEFAULT_STATUS_NORMAL.toString());
            myHttpClient.postJson(url, bo);
            uploadService.add(upload);
            try {
                if (!tempFile.delete()) {
                    log.error("删除本地临时文件错误：{}", fileName);
                }
            } catch (Exception e) {
                log.error("删除本地临时文件错误：{}", fileName);
            }
            return new ResponseInfo<>(retPath);
        } catch (Exception e) {
            new RuntimeException("文件上传失败");
            ResponseInfo info = new ResponseInfo();
            info.setCode("1");
            info.setMessage("上传失败");
            return info;
        }
    }
    
    @ApiOperation("文件上传")
    @PermitAll
    @UploadMapping("/file-report")
    public ResponseInfo<String> fileReport(@ApiParam("上传文件") @Valid @RequestParam(required = true) MultipartFile file,
            String filePath) {
        try {
            String directory = System.getProperty("java.io.tmpdir");
            String fileName = file.getOriginalFilename();
            File tempFile = new File(directory, fileName);
            file.transferTo(tempFile);//保存文件
            //把文件写入后再执行以下
            String retPath = fileService.upload(tempFile, filePath, true);
            
            try {
                if (!tempFile.delete()) {
                    log.error("删除本地临时文件错误：{}", fileName);
                }
            } catch (Exception e) {
                log.error("删除本地临时文件错误：{}", fileName);
            }
            
            return new ResponseInfo<>(retPath);
        } catch (Exception e) {
            new RuntimeException("文件上传失败");
            return new ResponseInfo<>("文件上传失败");
        }
    }
    
    @ApiOperation("解析上传研报")
    @PostMapping("/analyze-report")
    @PermitAll
    public ResponseInfo<String> analyzeReport(@ApiParam("研报信息") @RequestBody AnalyzeReportVO vo)
            throws JsonProcessingException {
        for (QueryUploadReportRespVO respVO : vo.getRespVOs()) {
            log.info(respVO.getMysqlId()+respVO.getSourceId());
            ReportUpload upload = uploadService.queryById(respVO.getMysqlId());
            String id = UUID.randomUUID().toString().trim().replaceAll("-", "");
            
            AppReport report = new AppReport();
            BeanUtils.copyProperties(respVO, report);
            report.setId(id);
            report.setUpdateUserId(upload.getCreateUserId().toString());
            report.setUpdateTime(new Date());
            report.setCreateUserId(upload.getCreateUserId().toString());
            report.setCreateTime(new Date());
            reportService.add(report);
            log.info(report.getSourceId());
            if (null == report.getSourceId()) {
                upload.setStatus(2);
            } else {
                upload.setStatus(3);
            }
            upload.setReportId(id);
            uploadService.modifyById(upload);
            for (QueryUploadReportRespVO.Pic pic : respVO.getPic()) {
                String picId = UUID.randomUUID().toString().trim().replaceAll("-", "");
                AppReportPic reportPic = new AppReportPic();
                BeanUtils.copyProperties(pic, reportPic);
                reportPic.setReportId(id);
                reportPic.setId(picId);
                reportPic.setUpdateTime(new Date());
                reportPic.setCreateTime(new Date());
                reportPic.setCreateUserId(upload.getCreateUserId().toString());
                reportPic.setUpdateUserId(upload.getCreateUserId().toString());
                appReportPicService.add(reportPic);
            }
        }
    
        return new ResponseInfo<>();
    }
    
    @ApiOperation("上传研报查看")
    @PostMapping("/query-upload-report")
    public ResponseInfo<QueryUploadReportRespVO> queryUploadReport(
            @ApiParam(value = "请求参数") @Valid @RequestBody QueryReportByIdVO vo) {
        QueryUploadReportRespVO respVO = new QueryUploadReportRespVO();
        AppReport report = reportService.queryById(vo.getId());
        if (report.getId() == null && report.getId().isEmpty()) {
            return new ResponseInfo(respVO);
        }
        AppReportPic appReportPic = new AppReportPic();
        BeanUtils.copyProperties(report, respVO);
        appReportPic.setReportId(report.getId());
        appReportPic.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        List<AppReportPic> appReportPics = appReportPicService.queryList(appReportPic);
        List<QueryUploadReportRespVO.Pic> list = new ArrayList<>();
        appReportPics.forEach(a -> {
            QueryUploadReportRespVO.Pic pic = new QueryUploadReportRespVO.Pic();
            BeanUtils.copyProperties(a, pic);
            list.add(pic);
        });
        respVO.setPic(list);
        TagRel tagRel = new TagRel();
        tagRel.setDataType(Constant.TAG_DATATYPE_REPORT);
        tagRel.setDataId(report.getId());
        if (report.getFilePath() != null && !report.getFilePath().isEmpty()) {
            respVO.setFilePath(HtmlUtils.filePathAppend(report.getFilePath(), url));
        }
        respVO.setLabels(tagRelService.queryList(tagRel));
        AppReportSentiment appReportSentiment = new AppReportSentiment();
        appReportSentiment.setReportId(report.getId());
        List<String> compIds = appReportSentimentService.queryList(appReportSentiment).stream().map(a -> a.getCompId()).collect(Collectors.toList());
        List<String> compNames = appReportSentimentService.queryList(appReportSentiment).stream()
                .map(a -> a.getEntity()).collect(Collectors.toList());
        if (respVO.getHtml() != null && respVO.getHtml() != "") {
            respVO.setHtml(HtmlUtils.replaceHtmlTag(respVO.getHtml(), minioAddress));
        }
        respVO.setCompIds(compIds);
        respVO.setCompNames(compNames);
    
        return new ResponseInfo<QueryUploadReportRespVO>(respVO);
    }
    
    @ApiOperation("热门行业")
    @PostMapping("/hot-industry")
    public ResponseInfo<List<HotIndustryDTO>> hotIndustry() {
        List<HotIndustryDTO> list = reportService.countIndustry();
        List<HotIndustryDTO> collect = list.stream().sorted((a, b) -> {
            if (a.getReports().equals(b.getReports())) {
                return a.getViewpoints().compareTo(b.getViewpoints());
            } else {
                return a.getReports().compareTo(a.getReports());
            }
        }).collect(Collectors.toList());
        return new ResponseInfo<>(collect);
    }
    
    @ApiOperation("推送策略列表")
    @PostMapping("/list-push-scheme")
    public ResponseInfo<PageResult<ListReportPushSchemeRespVO>> listPushScheme(@ApiParam("请求参数") @Valid @RequestBody ReqDTO<ListReportPushSchemeReqVO> dto) {
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        PageResult<ReportPushScheme> page = pageService.page(dto.getPageParam(),
                () -> schemeService.queryByStatus(dto.getContent().getStatus(), loginUser.getId()));
        List<ListReportPushSchemeRespVO> reportPushSchemes = new ArrayList<>();
        Map<String, Dict> reportLevel = dictService.queryDict("REPORT_LEVEL");
        Map<String, Dict> levelChange = dictService.queryDict("LEVEL_CHANGE");
        for (ReportPushScheme row : page.getRows()) {
            ListReportPushSchemeRespVO vo = new ListReportPushSchemeRespVO();
            BeanUtils.copyProperties(row, vo);
            ReportSchemeConfig config = new ReportSchemeConfig();
            config.setMonitoringId(row.getId());
            
            config.setTagType(Constant.SCHEME_CONFIG_TYPE_INDUSTRY);
            List<ReportSchemeConfig> industry = schemeConfigService.queryList(config);
            if (!industry.isEmpty()) {
                vo.setIndustryIds(industry.stream().map(c -> c.getTagId()).collect(Collectors.toList()));
                List<String> industryName = industryService.queryByIds(industry.stream().map(c -> c.getTagId()).collect(Collectors.toList())).stream()
                        .map(i -> i.getName()).collect(Collectors.toList());
                vo.setIndustryName(industryName);
            }
            
            config.setTagType(Constant.SCHEME_CONFIG_TYPE_REPORT);
            List<ReportSchemeConfig> type = schemeConfigService.queryList(config);
            
            if (!type.isEmpty()) {
                vo.setReport(type.stream().map(c -> c.getTagId()).collect(Collectors.toList()));
                List<String> reportName = reportTypeService.queryByIds(type.stream().map(c -> c.getTagId()).collect(Collectors.toList())).stream()
                        .map(d -> d.getName()).collect(Collectors.toList());
                vo.setReportName(reportName);
            }
            
            config.setTagType(Constant.SCHEME_CONFIG_TYPE_RATING);
            List<ReportSchemeConfig> rating = schemeConfigService.queryList(config);
            if (!rating.isEmpty()) {
                List<Long> tagId = rating.stream().map(c -> c.getTagId()).collect(Collectors.toList());
                vo.setRating(tagId);
                List<String> names = new ArrayList<>();
                tagId.forEach(t->{
                    Dict dict = dictService.queryDictByCode(reportLevel, t.toString());
                    if (null != dict)
                    names.add(dict.getBusiName());
                });
                vo.setRankChangeName(names);
            }
            config.setTagType(Constant.SCHEME_CONFIG_TYPE_RANK_CHANGE);
            List<ReportSchemeConfig> rankChange = schemeConfigService.queryList(config);
            if (!rankChange.isEmpty()) {
                List<Long> tagId = rankChange.stream().map(c -> c.getTagId()).collect(Collectors.toList());
                vo.setRankChange(tagId);
                List<String> names = new ArrayList<>();
                tagId.forEach(t->{
                    Dict dict = dictService.queryDictByCode(levelChange, t.toString());
                    if(null != dict)
                    names.add(dict.getBusiName());
                });
                vo.setRankChangeName(names);
            }
            config.setTagType(Constant.SCHEME_CONFIG_TYPE_DATA_SOURCE);
            List<ReportSchemeConfig> dataSource = schemeConfigService.queryList(config);
            if (!dataSource.isEmpty()){
                List<String> ds = dataSource.stream().map(d -> d.getTagValue()).collect(Collectors.toList());
                vo.setDataSource(ds);
            }
            
            config.setTagType(Constant.SCHEME_CONFIG_TYPE_SOURCE);
            List<ReportSchemeConfig> source = schemeConfigService.queryList(config);
            if (!source.isEmpty()){
                List<String> collect = source.stream().map(s -> s.getTagValue()).collect(Collectors.toList());
                vo.setSource(collect);
            }
    
            reportPushSchemes.add(vo);
        }
        PageResult<ListReportPushSchemeRespVO> pageResult = new PageResult<ListReportPushSchemeRespVO>();
        pageResult.setRows(reportPushSchemes);
        pageResult.setPage(page.getPage());
        return new ResponseInfo<PageResult<ListReportPushSchemeRespVO>>(pageResult);
    }
    
    @ApiOperation("添加推送策略")
    @PostMapping("/add-push-scheme")
    public ResponseInfo<Object> addPushScheme(@ApiParam("添加参数") @Valid @RequestBody EditPushSchemeReqVO vo) {
        
        ReportPushScheme reportPushScheme = new ReportPushScheme();
        ResponseInfo<Object> info = new ResponseInfo<>();
        reportPushScheme.setName(vo.getName());
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        reportPushScheme.setCreateUserId(loginUser.getId());
        OptLogReqVO vo1 = new OptLogReqVO();
        vo1.setOptType(6);
        vo1.setOptContent("添加"+vo.getName()+"策略方案");
        vo1.setOptModule(4);
        if (schemeService.queryList(reportPushScheme).isEmpty()) {
            reportPushScheme.setId(myIdGenerator.nextId());
            reportPushScheme.setName(vo.getName());
            reportPushScheme.setStatus(vo.getStatus());
            reportPushScheme.setCreateTime(new Date());
            reportPushScheme.setCreateUserId(loginUser.getId());
            schemeService.add(reportPushScheme);
            vo1.setStatus(1);
            logService.saveOptLog(vo1);
            return info;
        }
        info.setMessage("推送策略已存在");
        info.setCode("1");
        vo1.setStatus(2);
        logService.saveOptLog(vo1);
        return info;
    }
    
    @ApiOperation("修改推送策略")
    @PostMapping("/update-push-scheme")
    public ResponseInfo<Object> updatePushScheme(@ApiParam("修改参数") @Valid @RequestBody EditPushSchemeReqVO vo) {
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        OptLogReqVO vo1 = new OptLogReqVO();
        vo1.setOptType(5);
        vo1.setOptContent("编辑"+schemeService.queryById(vo.getId()).getName()+"策略方案");
        vo1.setOptModule(4);
        ResponseInfo info = new ResponseInfo();
        if (Constant.UPDATE_SCHEME.equals(vo.getStatus())) {
            ReportPushScheme scheme = new ReportPushScheme();
            scheme.setName(vo.getName());
            scheme.setCreateUserId(loginUser.getId());
           
            if (schemeService.queryList(scheme).isEmpty()) {
                ReportPushScheme reportPushScheme = new ReportPushScheme();
                reportPushScheme.setId(vo.getId());
                reportPushScheme.setName(vo.getName());
                reportPushScheme.setStatus(vo.getStatus());
    
                reportPushScheme.setUpdateTime(new Date());
                reportPushScheme.setUpdateUserId(loginUser.getId());
                schemeService.modifyById(reportPushScheme);
                vo1.setStatus(1);
                logService.saveOptLog(vo1);
                return info;
            }
            vo1.setStatus(2);
            logService.saveOptLog(vo1);
            info.setCode("1");
            info.setMessage("策略名重复");
            return info;
        }
        ReportPushScheme reportPushScheme = new ReportPushScheme();
        reportPushScheme.setId(vo.getId());
        reportPushScheme.setName(vo.getName());
        reportPushScheme.setStatus(vo.getStatus());
    
        reportPushScheme.setUpdateTime(new Date());
        reportPushScheme.setUpdateUserId(loginUser.getId());
        schemeService.modifyById(reportPushScheme);
        vo1.setStatus(1);
        logService.saveOptLog(vo1);
        return info;
        
    }
    
    @ApiOperation("已配置策略列表")
    @PostMapping("/list-scheme-config")
    public ResponseInfo<ListSchemeRespVO> listSchemeConfig(
            @ApiParam("查询参数") @Valid @RequestBody EditPushSchemeReqVO vo) {
        ListSchemeRespVO respVO = new ListSchemeRespVO();
        ReportSchemeConfig config = new ReportSchemeConfig();
        config.setMonitoringId(vo.getId());
        List<Long> industry = schemeConfigService.queryList(config).stream().filter(r -> {
            if (Constant.SCHEME_CONFIG_TYPE_INDUSTRY.equals(r.getTagType())) {
                return true;
            } else {
                return false;
            }
        }).map(r -> r.getTagId()).collect(Collectors.toList());
        List<Long> report = schemeConfigService.queryList(config).stream().filter(r -> {
            if (Constant.SCHEME_CONFIG_TYPE_REPORT.equals(r.getTagType())) {
                return true;
            } else {
                return false;
            }
        }).map(r -> r.getTagId()).collect(Collectors.toList());
        List<Long> rating = schemeConfigService.queryList(config).stream().filter(r -> {
            if (Constant.SCHEME_CONFIG_TYPE_RATING.equals(r.getTagType())) {
                return true;
            } else {
                return false;
            }
        }).map(r -> r.getTagId()).collect(Collectors.toList());
    
        List<Long> rankChange = schemeConfigService.queryList(config).stream().filter(r -> {
            if (Constant.SCHEME_CONFIG_TYPE_RANK_CHANGE.equals(r.getTagType())) {
                return true;
            } else {
                return false;
            }
        }).map(r -> r.getTagId()).collect(Collectors.toList());
        respVO.setRankChange(rankChange);
        respVO.setReport(report);
        respVO.setIndustry(industry);
        respVO.setRating(rating);
        return new ResponseInfo<ListSchemeRespVO>(respVO);
    }
    
    @ApiOperation("修改策略")
    @PostMapping("/update-scheme")
    public ResponseInfo<Object> updateScheme(@ApiParam("策略列表") @Valid @RequestBody EditConfigPushSchemeReqVO vo) {
        schemeConfigService.deleteByMonitoringId(vo.getId());
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        for (Long tagId : vo.getIndustry()) {
            ReportSchemeConfig schemeConfig = new ReportSchemeConfig();
            schemeConfig.setId(myIdGenerator.nextId());
            schemeConfig.setCreateUserId(loginUser.getId());
            schemeConfig.setCreateTime(new Date());
            schemeConfig.setMonitoringId(vo.getId());
            schemeConfig.setTagId(tagId);
            schemeConfig.setTagType(Constant.SCHEME_CONFIG_TYPE_INDUSTRY);
            schemeConfigService.add(schemeConfig);
        }
        for (Long tagId : vo.getReport()) {
            ReportSchemeConfig schemeConfig = new ReportSchemeConfig();
            schemeConfig.setId(myIdGenerator.nextId());
            schemeConfig.setCreateUserId(loginUser.getId());
            schemeConfig.setCreateTime(new Date());
            schemeConfig.setMonitoringId(vo.getId());
            schemeConfig.setTagId(tagId);
            schemeConfig.setTagType(Constant.SCHEME_CONFIG_TYPE_REPORT);
            schemeConfigService.add(schemeConfig);
        }
        for (Long tagId : vo.getRating()) {
            ReportSchemeConfig schemeConfig = new ReportSchemeConfig();
            schemeConfig.setId(myIdGenerator.nextId());
            schemeConfig.setCreateUserId(loginUser.getId());
            schemeConfig.setCreateTime(new Date());
            schemeConfig.setMonitoringId(vo.getId());
            schemeConfig.setTagId(tagId);
            schemeConfig.setTagType(Constant.SCHEME_CONFIG_TYPE_RATING);
            schemeConfigService.add(schemeConfig);
        }
        for (Long tagId : vo.getRankChange()) {
            ReportSchemeConfig schemeConfig = new ReportSchemeConfig();
            schemeConfig.setId(myIdGenerator.nextId());
            schemeConfig.setCreateUserId(loginUser.getId());
            schemeConfig.setCreateTime(new Date());
            schemeConfig.setMonitoringId(vo.getId());
            schemeConfig.setTagId(tagId);
            schemeConfig.setTagType(Constant.SCHEME_CONFIG_TYPE_RANK_CHANGE);
            schemeConfigService.add(schemeConfig);
        }
        return new ResponseInfo<Object>();
    }
    
    @ApiOperation("配置策略")
    @PostMapping("/config-push-scheme")
    public ResponseInfo<Object> configPushScheme(@ApiParam("策略列表") @Valid @RequestBody EditConfigPushSchemeReqVO vo) {
        schemeConfigService.deleteByMonitoringId(vo.getId());
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        for (Long tagId : vo.getIndustry()) {
            ReportSchemeConfig schemeConfig = new ReportSchemeConfig();
            schemeConfig.setId(myIdGenerator.nextId());
            schemeConfig.setCreateUserId(loginUser.getId());
            schemeConfig.setCreateTime(new Date());
            schemeConfig.setMonitoringId(vo.getId());
            schemeConfig.setTagId(tagId);
            schemeConfig.setTagType(Constant.SCHEME_CONFIG_TYPE_INDUSTRY);
            schemeConfigService.add(schemeConfig);
        }
        for (Long tagId : vo.getReport()) {
            ReportSchemeConfig schemeConfig = new ReportSchemeConfig();
            schemeConfig.setId(myIdGenerator.nextId());
            schemeConfig.setCreateUserId(loginUser.getId());
            schemeConfig.setCreateTime(new Date());
            schemeConfig.setMonitoringId(vo.getId());
            schemeConfig.setTagId(tagId);
            schemeConfig.setTagType(Constant.SCHEME_CONFIG_TYPE_REPORT);
            schemeConfigService.add(schemeConfig);
        }
        for (Long tagId : vo.getRating()) {
            ReportSchemeConfig schemeConfig = new ReportSchemeConfig();
            schemeConfig.setId(myIdGenerator.nextId());
            schemeConfig.setCreateUserId(loginUser.getId());
            schemeConfig.setCreateTime(new Date());
            schemeConfig.setMonitoringId(vo.getId());
            schemeConfig.setTagId(tagId);
            schemeConfig.setTagType(Constant.SCHEME_CONFIG_TYPE_RATING);
            schemeConfigService.add(schemeConfig);
        }
        for (Long tagId : vo.getRankChange()) {
            ReportSchemeConfig schemeConfig = new ReportSchemeConfig();
            schemeConfig.setId(myIdGenerator.nextId());
            schemeConfig.setCreateUserId(loginUser.getId());
            schemeConfig.setCreateTime(new Date());
            schemeConfig.setMonitoringId(vo.getId());
            schemeConfig.setTagId(tagId);
            schemeConfig.setTagType(Constant.SCHEME_CONFIG_TYPE_RANK_CHANGE);
            schemeConfigService.add(schemeConfig);
        }
        if (null != vo.getDataSource() && !vo.getDataSource().isEmpty()){
            for (String s : vo.getDataSource()) {
                ReportSchemeConfig schemeConfig = new ReportSchemeConfig();
                schemeConfig.setId(myIdGenerator.nextId());
                schemeConfig.setCreateUserId(loginUser.getId());
                schemeConfig.setCreateTime(new Date());
                schemeConfig.setMonitoringId(vo.getId());
                schemeConfig.setTagValue(s);
                schemeConfig.setTagType(Constant.SCHEME_CONFIG_TYPE_DATA_SOURCE);
                schemeConfigService.add(schemeConfig);
            }
        }
        if (null != vo.getSource() && !vo.getSource().isEmpty()){
            for (String s : vo.getSource()) {
                ReportSchemeConfig schemeConfig = new ReportSchemeConfig();
                schemeConfig.setId(myIdGenerator.nextId());
                schemeConfig.setCreateUserId(loginUser.getId());
                schemeConfig.setCreateTime(new Date());
                schemeConfig.setMonitoringId(vo.getId());
                schemeConfig.setTagValue(s);
                schemeConfig.setTagType(Constant.SCHEME_CONFIG_TYPE_SOURCE);
                schemeConfigService.add(schemeConfig);
            }
        }
        OptLogReqVO vo1 = new OptLogReqVO();
        vo1.setStatus(1);
        vo1.setOptModule(4);
        vo1.setOptType(9);
        vo1.setOptContent("配置"+schemeService.queryById(vo.getId()).getName()+"策略方案");
        logService.saveOptLog(vo1);
        
        
        return new ResponseInfo<>();
    }
    
    @ApiOperation("根据id查询")
    @PostMapping("/query-report-by-id")
    public ResponseInfo<ListReportRespVO> queryReportById(
            @ApiParam(value = "请求参数") @Valid @RequestBody QueryReportByIdVO vo) {
        Map<String, Dict> reportLevel = dictService.queryDict("REPORT_LEVEL");
        Map<String, Dict> levelChange = dictService.queryDict("LEVEL_CHANGE");
        AppReport report = reportService.queryById(vo.getId());
        ListReportRespVO respVO = new ListReportRespVO();
        try {
            BeanUtils.copyProperties(report, respVO);
        }catch (Exception e){
            throw new RuntimeException("查询研报错误,"+vo.getId()+"不存在");
        }
        if (null != report.getRank()){
            respVO.setRankName(dictService.queryDictByCode(reportLevel,report.getRank().toString()).getBusiName());
        }
        if (null != report.getRankChange()){
            respVO.setRankChangeName(dictService.queryDictByCode(levelChange,report.getRankChange().toString()).getBusiName());
        }
//        if (null != report.getType() && null != reportTypeService.queryById(report.getType().longValue())){
//            respVO.setTypeName(reportTypeService.queryById(report.getType().longValue()).getName());
//        }
        respVO.setEmotionProport(report.getEmotionProport().setScale(2, RoundingMode.HALF_UP));

        TagRel tagRel = new TagRel();
        tagRel.setDataType(Constant.TAG_DATATYPE_REPORT);
        tagRel.setDataId(report.getId());
        if (report.getFilePath() != null && !report.getFilePath().isEmpty()) {
            respVO.setFilePath(HtmlUtils.filePathAppend(report.getFilePath(), minioAddress));
        }
        respVO.setLabels(tagRelService.queryList(tagRel));
        AppReportSentiment appReportSentiment = new AppReportSentiment();
        appReportSentiment.setReportId(report.getId());
        List<String> compIds = appReportSentimentService.queryList(appReportSentiment).stream().map(a -> a.getCompId()).collect(Collectors.toList());
        List<String> compNames = appReportSentimentService.queryList(appReportSentiment).stream()
                .map(a -> a.getEntity()).collect(Collectors.toList());
        if (respVO.getHtml() != null && respVO.getHtml() != "") {
            respVO.setHtml(HtmlUtils.replaceHtmlTag(respVO.getHtml(), minioAddress));
        }
        if(null != report.getSentiment()){
            if (Constant.SENTIMENT_POSITIVE.equals(report.getSentiment())) {
                respVO.setSentiment("积极");
            }
            if (Constant.SENTIMENT_NEUTRAL.equals(report.getSentiment())) {
                respVO.setSentiment("中立");
            }
            if (Constant.SENTIMENT_NEGATIVE.equals(report.getSentiment())) {
                respVO.setSentiment("消极");
            }
        }
        respVO.setCompIds(compIds);
        respVO.setCompNames(compNames);
        AppReportPic pic = new AppReportPic();
        pic.setReportId(report.getId());
        List<AppReportPic> pics = appReportPicService.queryList(pic);
        List<ListReportRespVO.Pic> list = new ArrayList<>();
        for (AppReportPic appReportPic : pics) {
            ListReportRespVO.Pic p = new ListReportRespVO.Pic();
            BeanUtils.copyProperties(appReportPic, p);
            if(null != appReportPic.getUrl()){
                p.setUrl(minioAddress+appReportPic.getUrl());
            }
            list.add(p);
        }
        respVO.setPic(list);
        respVO.setInfoType(3);
        //是否已收藏
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        CollectInfo collect = new CollectInfo();
        collect.setInfoId(Long.getLong(vo.getId()));
        collect.setCreateUserId(loginUser.getId());
        List<CollectInfo> collectList = collectInfoService.queryList(collect);
        if(!collectList.isEmpty()){
            respVO.setCollect(Constant.WHETHER_YES);
        }
        else{
            respVO.setCollect(Constant.WHETHER_NO);
        }

        return new ResponseInfo<ListReportRespVO>(respVO);
    }

    @ApiOperation("最新研报")
    @PostMapping("/new-report")
    public ResponseInfo<PageResult<ListReportRespVO>> newReport(
            @ApiParam(value = "请求参数") @Valid @RequestBody ReqDTO<Object> dto) {
        PageResult<AppReport> page = pageService.page(dto.getPageParam(), () -> reportService.queryList(new AppReport()));
        List<ListReportRespVO> list = new ArrayList<>();
        Map<String, Dict> reportLevel = dictService.queryDict("REPORT_LEVEL");
        Map<String, Dict> levelChange = dictService.queryDict("LEVEL_CHANGE");
        List<String> reportIds = page.getRows().stream().map(a -> a.getId()).collect(Collectors.toList());
        List<TagRel> tagRels = tagRelService.queryByTagIds(reportIds,Constant.TAG_DATATYPE_REPORT);
        List<AppReportSentiment> appReportSentiments = appReportSentimentService.queryByReportIds(reportIds);
        
        for (AppReport report : page.getRows()) {
            ListReportRespVO vo = new ListReportRespVO();
            BeanUtils.copyProperties(report, vo);
            if (report.getHtml() != null) {
                vo.setHtml(HtmlUtils.replaceHtmlTag(report.getHtml(), minioAddress));
            }
            
            if (report.getFilePath() != null && !report.getFilePath().isEmpty()) {
                vo.setFilePath(HtmlUtils.filePathAppend(report.getFilePath(), minioAddress));
            }
            List<TagRel> labels = new ArrayList<>();
            for(TagRel obj : tagRels){
                if(obj.getDataId().equals(report.getId())){
                    labels.add(obj);
                }
            }
            vo.setLabels(labels);

            List<String> compIds = new ArrayList<>();
            List<String> compNames = new ArrayList<>();
            for(AppReportSentiment obj : appReportSentiments){
                if(obj.equals(report.getId())){
                    compIds.add(obj.getCompId());
                    compNames.add(obj.getEntity());
                }
            }
            
            vo.setCompIds(compIds);
            if (compNames.size() > 10){
                compNames = compNames.subList(0,10);
            }
            vo.setCompNames(compNames);
            if (vo.getHtml() != null && vo.getHtml() != "") {
                vo.setHtml(HtmlUtils.replaceHtmlTag(vo.getHtml(), minioAddress));
            }
//            if (null != report.getType()){
//                if (null != reportTypeService.queryById(report.getType().longValue())){
//                    vo.setTypeName(reportTypeService.queryById(report.getType().longValue()).getName());
//                }
//
//            }
            if (null != vo.getRank()){
                vo.setRankName(dictService.queryDictByCode(reportLevel,vo.getRank().toString()).getBusiName());
            }
            if (null != vo.getRankChange()){
                vo.setRankChangeName(dictService.queryDictByCode(levelChange,vo.getRankChange().toString()).getBusiName());
            }
            list.add(vo);
        }
        PageResult<ListReportRespVO> pageResult = new PageResult<>();
        pageResult.setPage(page.getPage());
        pageResult.setRows(list);
        return new ResponseInfo<PageResult<ListReportRespVO>>(pageResult);
    }
    
    @ApiOperation("根据id查询图表")
    @PostMapping("/query-pic-id")
    public ResponseInfo<ListPicDTO> queryPicById(@ApiParam(value = "请求参数") @Valid @RequestBody PicVO vo) {
        ListPicDTO listPicDTOS = picService.queryByPic(vo.getId());
        listPicDTOS.setUrl(minioAddress+listPicDTOS.getUrl());
        TagRel tagRel = new TagRel();
        tagRel.setDataId(Constant.TAG_DATATYPE_REPORT.toString());
        tagRel.setDataId(listPicDTOS.getReportId());
        List<TagRel> tagRels = tagRelService.queryList(tagRel);
        listPicDTOS.setLabels(tagRels);
        return new ResponseInfo<ListPicDTO>(listPicDTOS);
    }
    
    @ApiOperation("首页推送列表")
    @PostMapping("/page-removal-report")
    public ResponseInfo<List<ListReportRespVO>> pageRemovalReport() {
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        
        List<ListReportRespVO> list = new ArrayList<>();
        
        List<ReportSchemeConfig> configs = schemeConfigService.queryConfig(loginUser.getId());
        if (configs.isEmpty()){
            return new ResponseInfo<>(new ArrayList<>());
        }
        List<Long> industry = configs.stream().filter(c -> {
            if (c.getTagType().equals(Constant.SCHEME_CONFIG_TYPE_INDUSTRY)) {
                return true;
            } else {
                return false;
            }
        }).map(c -> c.getTagId()).collect(Collectors.toList());
    
        
        List<Integer> report = configs.stream().filter(c -> {
            if (c.getTagType().equals(Constant.SCHEME_CONFIG_TYPE_REPORT)) {
                return true;
            } else {
                return false;
            }
        }).map(c -> c.getTagId().intValue()).collect(Collectors.toList());
    
        List<Integer> rank = configs.stream().filter(c -> {
            if (c.getTagType().equals(Constant.SCHEME_CONFIG_TYPE_RATING)) {
                return true;
            } else {
                return false;
            }
        }).map(c->c.getTagId().intValue()).collect(Collectors.toList());
    
        List<Integer> rc = configs.stream().filter(c -> {
            if (c.getTagType().equals(Constant.SCHEME_CONFIG_TYPE_RANK_CHANGE)) {
                return true;
            } else {
                return false;
            }
        }).map(c->c.getTagId().intValue()).collect(Collectors.toList());
    
        List<String> ds = configs.stream().filter(c -> {
            if (c.getTagType().equals(Constant.SCHEME_CONFIG_TYPE_DATA_SOURCE)) {
                return true;
            } else {
                return false;
            }
        }).map(c -> c.getTagValue()).collect(Collectors.toList());
    
        List<String> s = configs.stream().filter(c -> {
            if (c.getTagType().equals(Constant.SCHEME_CONFIG_TYPE_SOURCE)) {
                return true;
            } else {
                return false;
            }
        }).map(c -> c.getTagValue()).collect(Collectors.toList());
    
        
        if (rank.isEmpty() && report.isEmpty() && rc.isEmpty() &&industry.isEmpty() && ds.isEmpty() && s.isEmpty()){
            return new ResponseInfo<>(new ArrayList<>());
        }
        ListReportPushDTO pushDTO = new ListReportPushDTO();
        pushDTO.setRank(rank);
        pushDTO.setType(report);
        pushDTO.setRankChange(rc);
        pushDTO.setDataSource(ds);
        pushDTO.setSource(s);
        List<String> industryIds = new ArrayList<>();
        industry.forEach(i->{
            String substring = industryService.queryIndustry(i).getCode().substring(0, 4)+"%";
            industryIds.add(substring);
        });
        pushDTO.setIndustryIds(industryIds);
        List<AppReport> appReports = reportService.queryListReportByScheme(pushDTO);
        List<String> reportIds = appReports.stream().map(a -> a.getId()).collect(Collectors.toList());
        List<AppReportSentiment> appReportSentiments = appReportSentimentService.queryByReportIds(reportIds);
        Map<String, Dict> reportLevel = dictService.queryDict("REPORT_LEVEL");
        Map<String, Dict> levelChange = dictService.queryDict("LEVEL_CHANGE");
        List<TagRel> tagRels = tagRelService
                .queryByTagIds(reportIds,
                        Constant.SCHEME_CONFIG_TYPE_RATING);
        for (AppReport row : appReports) {
            ListReportRespVO vo = new ListReportRespVO();
            BeanUtils.copyProperties(row,vo);
            List<String> names = appReportSentiments.stream().filter(a -> {
                if (a.getReportId().equals(row.getId())) {
                    return true;
                } else {
                    return false;
                }
            }).map(a -> a.getEntity()).collect(Collectors.toList());
            if (names.size()>10){
                names = names.subList(0,10);
            }
            vo.setCompNames(names);
            if (!tagRels.isEmpty()){
                List<TagRel> tagNames = tagRels.stream().filter(t -> {
                    if (row.getId().equals(t.getDataId())) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
                vo.setLabels(tagNames);
            }
            if (null != row.getRank()){
                vo.setRankName(dictService.queryDictByCode(reportLevel,row.getRank().toString()).getBusiName());
            }
            if (null != row.getRankChange()){
                vo.setRankChangeName(dictService.queryDictByCode(levelChange,row.getRankChange().toString()).getBusiName());
            }
            if (null != row.getType()){
                ReportType rt = reportTypeService.queryReportType(row.getType().longValue());
                if(null != rt){
                    vo.setTypeName(rt.getName());
                }
            }
            list.add(vo);
        }
      
        return new ResponseInfo(list);
    }
    
    
    @ApiOperation("下载研报")
    @DownloadMapping("/download-report")
    public void downloadReport(@ApiParam("下载参数") DownloadReportReqVO vo, HttpServletResponse response) throws IOException {
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        
        String filePath = reportService.queryById(vo.getId()).getFilePath();
        String fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
        if(fileName.isEmpty()){
            fileName = filePath;
        }
        String ext = fileName.substring(fileName.lastIndexOf('.'));
    
        String directory = System.getProperty("java.io.tmpdir");
        File file = new File(directory,fileName);
        fileService.download(filePath,file);

        File file2 = File.createTempFile(UUID.randomUUID().toString(),ext);
        String waterMark = loginUser.getUserCode() + " " + loginUser.getName();
        File downFile = file2;
        if(ext.toLowerCase().equals(".pdf")){
            FileUtils.waterMarkPdf(file.getPath(),file2.getPath(),waterMark);
        }
//        else if(ext.toLowerCase().equals(".doc")){
//            //todo word
//            FileUtils.waterMarkPdf(file.getPath(),file2.getPath(),waterMark);
//        }
        else{
            downFile = file;
        }
    
        localFileService.download(downFile.getPath(), response);
        try {
            if(!file.delete()){
                log.error("删除本地临时文件错误：{}" , directory+"/"+fileName);
            }
            if(!file2.delete()){
                log.error("删除本地临时文件错误" );
            }
        }
        catch (Exception e) {
            log.error("删除本地临时文件错误：{}" , directory+"/"+fileName);
        }
    }
    
    
    
    @ApiOperation("数据来源")
    @PostMapping("/data-source")
    public ResponseInfo<List<DataSourceCount>> dataSource(){
        List<DataSourceCount> dataSource = reportService.queryDataSource();
        return new ResponseInfo(dataSource);
    }
    
    @ApiOperation("来源机构")
    @PostMapping("/source-agency")
    public ResponseInfo<PageResult<SourceAgencyDTO>> sourceAgency(@ApiParam("查询参数") @RequestBody ReqDTO<QuerySourceAgencyReqVO> dto){
    
        PageResult<SourceAgencyDTO> page = reportPushService.querySourceAgency(dto);
        return new ResponseInfo(page);
    }
    
    @ApiOperation("研报页数")
    @PostMapping("/report-page")
    public ResponseInfo<List<CountPageDTO>> reportPage(){
        List<CountPageDTO> countPageDTOS = reportService.countPage();
        return new ResponseInfo(countPageDTOS);
    }

    @ApiOperation("根据行业code查询二级行业类型的行业研报")
    @PostMapping("/queryTwoNumReport-code")
    public ResponseInfo<List<ReportCodeDTO>> queryTwoReportByNumCode(@ApiParam(value = "行业code") @Valid @RequestBody ReportCodeReqVO vo) {
        log.info("ReportController.queryTwoReportByNumCode start...");
        List<ReportCodeReqDTO> reportCodeReqDTOList = reportService.queryTwoByIndustryCode(vo.getCode().substring(0,2));
        IndustrySw industrySw = new IndustrySw();
        industrySw.setCode(vo.getCode().substring(0,2));
        industrySw.setLevel(2);
        List<IndustrySw> industrySwList = industrySwService.querySubList(industrySw);
        return getListResponseInfo(reportCodeReqDTOList, industrySwList);
    }

    @ApiOperation("根据行业code查询三级行业类型的行业研报")
    @PostMapping("/queryThreeNumReport-code")
    public ResponseInfo<List<ReportCodeDTO>> queryThreeReportByIndustryCode(@ApiParam(value = "行业code") @Valid @RequestBody ReportCodeReqVO vo) {
        log.info("ReportController.queryThreeReportByIndustryCode start...");
        List<ReportCodeReqDTO> reportCodeReqDTOList = reportService.queryThreeByIndustryCode(vo.getCode().substring(0,4));
        IndustrySw industrySw = new IndustrySw();
        industrySw.setCode(vo.getCode().substring(0,4));
        industrySw.setLevel(3);
        List<IndustrySw> industrySwList = industrySwService.querySubList(industrySw);
        return getListResponseInfo(reportCodeReqDTOList, industrySwList);
    }

    private ResponseInfo<List<ReportCodeDTO>> getListResponseInfo(List<ReportCodeReqDTO> reportCodeReqDTOList, List<IndustrySw> industrySwList) {
        List<ReportCodeDTO> reportCodeDTOList = reportService.getAllReportIndustry(reportCodeReqDTOList,industrySwList);
        log.info("********reportCodeDTOList的大小为***********："+reportCodeDTOList.size());
        if(!reportCodeDTOList.isEmpty()){
            reportCodeDTOList = reportCodeDTOList.stream().sorted((b, a) -> -a.getIndustryId().compareTo(b.getIndustryId())).collect(Collectors.toList());

        }
        return new ResponseInfo<>(reportCodeDTOList);
    }

    @ApiOperation("根据行业code查询四级行业类型的行业研报")
    @PostMapping("/queryFourNumReport-code")
    public ResponseInfo<List<ReportCodeDTO>> queryFourReportByIndustryCode(@ApiParam(value = "行业code") @Valid @RequestBody ReportCodeReqVO vo) {
        log.info("ReportController.queryFourReportByIndustryCode start...");
        List<ReportCodeReqDTO> reportCodeReqDTOList = reportService.queryFourByIndustryCode(vo.getCode().substring(0,6));
        IndustrySw industrySw = new IndustrySw();
        industrySw.setCode(vo.getCode().substring(0,6));
        industrySw.setLevel(4);
        List<IndustrySw> industrySwList = industrySwService.querySubList(industrySw);
        List<ReportCodeDTO> reportCodeDTOList = reportService.getAllReportIndustry(reportCodeReqDTOList,industrySwList);
        log.info("********reportCodeRespVOList的大小为***********："+reportCodeDTOList.size());
        if(!reportCodeDTOList.isEmpty()){
            reportCodeDTOList = reportCodeDTOList.stream().sorted((b, a) -> -a.getCreateTime().compareTo(b.getCreateTime())).collect(Collectors.toList());

        }
        return new ResponseInfo<>(reportCodeDTOList);
    }
    
    @ApiOperation("查询行业大类的行业研报")
    @PostMapping("/queryAllReport-Industry")
    public ResponseInfo<List<ReportCodeDTO>> queryAllReportIndustry() {
        log.info("ReportController.queryAllReportIndustry start...");
        List<ReportCodeReqDTO> reportCodeReqDTOList = reportService.queryAllIndustry();
        IndustrySw industrySw = new IndustrySw();
        industrySw.setLevel(1);
        List<IndustrySw> industrySwList = industrySwService.querySubListByOneLevel(industrySw);
        List<ReportCodeDTO> reportCodeDTOList = reportService.getAllReportIndustry(reportCodeReqDTOList,industrySwList);
        log.info("********reportCodeRespVOList的大小为***********："+reportCodeDTOList.size());
        if(!reportCodeDTOList.isEmpty()){
            reportCodeDTOList = reportCodeDTOList.stream().sorted((b, a) -> -a.getIndustryId().compareTo(b.getIndustryId())).collect(Collectors.toList());

        }
        return new ResponseInfo<>(reportCodeDTOList);
    }


}

